package com.magiccompass.alipay.barcode.security.controller;

import java.util.Collection;
import java.util.Iterator;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
public class LoginController {
	private static Logger logger = LogManager.getLogger(LoginController.class.getName());
	
	@RequestMapping(value = "/login", method = {RequestMethod.GET,RequestMethod.POST})
    public String basePage() {    	
    	return "login";
	}
	
	@RequestMapping(value = "/denied", method = RequestMethod.GET)
    public String loginError(ModelMap model) {
        model.addAttribute("error", "true");
        return "login";
    }
	
	@RequestMapping(value = "/header", method = RequestMethod.GET)
    public String header(ModelMap model) {
        return "header";
    }
	
	@RequestMapping(value = "/footer", method = RequestMethod.GET)
    public String footer(ModelMap model) {
        return "footer";
    }
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(ModelMap model) {
        return "redirect:/login";
    }
	
	@RequestMapping(value = {"/home","/"}, method = RequestMethod.GET)
    public String doLogin(ModelMap model) {
		logger.info("start to doLogin");
		String returnPage = getAfterLoginRedirectPage();
		return returnPage;
	}
	
	private String getAfterLoginRedirectPage(){
		String returnPage = "/login";
		UserDetails loginUser = getCurrentLoginUserDetails();
		Collection loginUserRoles = loginUser.getAuthorities();		
		String aRoleDesc;
		for (Iterator<GrantedAuthority> it = loginUserRoles.iterator(); it.hasNext(); ){
			aRoleDesc = it.next().getAuthority();
			if("ROLE_ADMIN".equals(aRoleDesc)){
				returnPage = "/admin/home";
				break;
			}else if("ROLE_MERCHANT".equals(aRoleDesc)){
				returnPage = "/merchant/home";
			}else if("ROLE_MERCHANT_GROUP_ADMIN".equals(aRoleDesc)){
				returnPage = "/merchantGroupAdmin/home";
			}
		}
		return returnPage;
	}
	
	private UserDetails getCurrentLoginUserDetails(){
		return (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	}
}
